require("Script.GameConfigs.GlobalConfigs");
local AC_Main_UI = {
    -- 游戏开始标记
    BGameStart = true;
}; 

function AC_Main_UI:InitBindEvent()
    -- UGCEventSystem:AddListener(AeroplaneChessEventType.TeamIndexAssigned, self.OnTeamIndexAssigned, self);
    UGCEventSystem:AddListener(EventType.PlayerInfosChanged, self.OnPlayerInfosChanged, self);
    UGCEventSystem:AddListener(EventType.PlayerPanelChange, self.OnShowPlayerPanel, self);
    UGCEventSystem:AddListener(EventType.GameStartChanged, self.OnGameStartChanged, self);
    UGCEventSystem:AddListener(EventType.CurTeamIndexChanged, self.ForceUpdateUI, self);
    UGCEventSystem:AddListener(EventType.PrepareStageRemainTimeChanged, self.OnPrepareStageRemainTimeChanged, self);
    UGCEventSystem:AddListener(EventType.CurRoundRemainTimeChanged, self.OnCurRoundRemainTimeChanged, self);
    UGCEventSystem:AddListener(EventType.CurRoundStatusChanged, self.ForceUpdateUI, self);
    UGCEventSystem:AddListener(EventType.PlayerStartNewRound, self.OnPlayerStartNewRound, self);
    --UGCEventSystem:AddListener(EventType.PlayCard, self.OnPlayCard, self);
    UGCEventSystem:AddListener(EventType.UpdateCardUI, self.OnUpdateCardUI, self);
end

function AC_Main_UI:UnBindEvents()
    -- UGCEventSystem:RemoveListener(AeroplaneChessEventType.TeamIndexAssigned, self.OnTeamIndexAssigned, self);
    UGCEventSystem:RemoveListener(EventType.PlayerInfosChanged, self.OnPlayerInfosChanged, self);
    UGCEventSystem:RemoveListener(EventType.PlayerPanelChange, self.OnShowPlayerPanel, self);
    UGCEventSystem:RemoveListener(EventType.GameStartChanged, self.OnGameStartChanged, self);
    UGCEventSystem:RemoveListener(EventType.CurTeamIndexChanged, self.ForceUpdateUI, self);
    UGCEventSystem:RemoveListener(EventType.PrepareStageRemainTimeChanged, self.OnPrepareStageRemainTimeChanged, self);
    UGCEventSystem:RemoveListener(EventType.CurRoundRemainTimeChanged, self.OnCurRoundRemainTimeChanged, self);
    UGCEventSystem:RemoveListener(EventType.CurRoundStatusChanged, self.ForceUpdateUI, self);
    UGCEventSystem:RemoveListener(EventType.PlayerStartNewRound, self.OnPlayerStartNewRound, self);
    --UGCEventSystem:RemoveListener(EventType.PlayCard, self.OnPlayCard, self);
    UGCEventSystem:RemoveListener(EventType.UpdateCardUI, self.OnUpdateCardUI, self);
end

-- 分配到了位置
--[[
function AC_Main_UI:OnTeamIndexAssigned(teamIndex, playerKey)
    print(string.format("AC_Main_UI:OnTeamIndexAssigned[%d] for Player[%d]", teamIndex, playerKey))
    if UGCGameSystem.GameState.CurrentGamestate ~= EGameStatus.WaitReady then
        print("UGCGameSystem.GameState.CurrentGamestate ~= EGameStatus.WaitReady, CurrentGamestate is:" .. tostring(UGCGameSystem.GameState.CurrentGamestate));
        return;
    end
    if AeroplaneChessMode.OwnerPlayerKey == playerKey then
        -- 四个飞机所在地板高亮
        for index = 1, 4 do
            local plane = UGCGameSystem.GameState.PlayerInfos[teamIndex].PlaneInfos[index]
            plane:GetCurTile():SetTileHighlight(true)
        end
    end
end
]]--

-- UI相关的函数
function AC_Main_UI:OnPlayerInfosChanged(playerInfo)
    log_tree_dev(playerInfo)
    self:UpdateAutoPlayUI()
    self:UpdateWatchingUI(playerInfo);
end

-- UI相关的函数
function AC_Main_UI:OnShowPlayerPanel(PlayerInfos)
    for i, PlayerState in ipairs(PlayerInfos) do

        if PlayerInfos[i].PlayerName ~= nil then
            self.PlayerID[i].TextBlock_Name:SetText(PlayerInfos[i].PlayerName)
            --self.PlayerID[i].TextBlock_Rank:SetText(i)
        end
        self.PlayerID[i].WidgetSwitcher_Tips:SetActiveWidgetIndex(i - 1)
        self.PlayerID[i].TextBlock_Rank:SetText(i)
        self.PlayerID[i].TextBlock_Score:SetText(tostring(math.ceil(PlayerInfos[i].EliminateNum)))
    end
end

-- 游戏开始提示
function AC_Main_UI:OnGameStartChanged()
    self.AC_GameStart_Tips_UIBP:Show(true);
end

-- 刷新界面UI
function AC_Main_UI:ForceUpdateUI()
    if UGCGameSystem.GameState == nil or AeroplaneChessMode == nil or Mode.OwnerPlayerState == nil then
        return;
    end
    if UGCGameSystem.GameState.CurrentGamestate == EGameStatus.Gaming then
        if Mode.IsTeamIndexValid(UGCGameSystem.GameState.CurRoundTeamIndex) then
            self.CurTeamIndex = UGCGameSystem.GameState.CurRoundTeamIndex
            self.IsMyRound = self.CurTeamIndex == Mode.OwnerPlayerState.TeamIndex
            print(string.format("AC_Main_UI:ForceUpdateUI: P[%d] IsMyRound:%s", self.CurTeamIndex, tostring(self.IsMyRound)));
            -- 选择卡牌按钮，注意是按钮
            local shouldShowSelectCard = self.IsMyRound and UGCGameSystem.GameState.CurRoundStatus == ERoundStatus.WaitForSelectCard
            self.Customizethrow:SetVisibility(shouldShowSelectCard and ESlateVisibility.SelfHitTestInvisible or ESlateVisibility.Collapsed)
            -- 飞机选择面板
            --local shouldShowPlaneSelection = self.IsMyRound and UGCGameSystem.GameState.CurRoundStatus == ERoundStatus.WaitForPlaneSelection
            --self:ShowPlaneSelectionPanel(shouldShowPlaneSelection)
            -- 只有在游戏中阶段才需要更新托管UI
            --self:UpdateAutoPlayUI()
        end
    else
        self.Customizethrow:SetVisibility(ESlateVisibility.Collapsed)
        --self:ShowPlaneSelectionPanel(false)
    end
end

-- 准备阶段倒计时更新,todo UI
function AC_Main_UI:OnPrepareStageRemainTimeChanged(RemainTime)
    ugcprint(string.format("AC_Main_UI:OnPrepareStageRemainTimeChanged RemainTime[%f]", RemainTime))
   --剩余时间小于0时隐藏倒计时UI
    if RemainTime > 0 then
        self.PrepareStageRemainTime:SetVisibility(ESlateVisibility.SelfHitTestInvisible)
        self.PrepareStageRemainTime.PrepareStageRemainTime_Text:SetText(tostring(math.ceil(RemainTime)))
    else
        self.PrepareStageRemainTime:SetVisibility(ESlateVisibility.Collapsed);
        -- 去除自身的高亮
        local myTeamIndex = self:GetMyTeamIndex()
        if myTeamIndex then
            for index = 1, 4 do
                local plane = UGCGameSystem.GameState.PlayerInfos[myTeamIndex].PlaneInfos[index]
                plane:GetCurTile():SetTileHighlight(false)
            end
        end
	end
end

-- 当前回合倒计时更新
function AC_Main_UI:OnCurRoundRemainTimeChanged(RemainTime)
    if UGCGameSystem.GameState.ShowRemainTime then
        ugcprint(string.format("AC_Main_UI:OnCurRoundRemainTimeChanged RemainTime[%f]", RemainTime))
        self.AC_RoundCountdown_UIBP:SetVisibility(ESlateVisibility.SelfHitTestInvisible);
        self.AC_RoundCountdown_UIBP.TextBlock_Time:SetText(""..math.ceil(RemainTime))
        if RemainTime <= 0 then
            self.AC_RoundCountdown_UIBP:SetVisibility(ESlateVisibility.Collapsed);
        end
    else
        if UE.IsValid(self) then
            self.AC_RoundCountdown_UIBP:SetVisibility(ESlateVisibility.Collapsed);
        end
    end
end

-- 玩家开始回合
function AC_Main_UI:OnPlayerStartNewRound(TeamIndex, PlayerKey, IsPlayAnotherRound)
    if not UE.IsValid(self) then return end
    if self.CurTeamIndex == TeamIndex and not IsPlayAnotherRound then return end
    ugcprint(string.format("AC_Main_UI:OnPlayerStartNewRound: P[%d] %s", TeamIndex, ETeameColor[TeamIndex]));
    -- 这里不刷新UI了，直接在同步变量时刷新
    -- self:ForceUpdateUI()
    self.IsMyRound = PlayerKey == AeroplaneChessMode.OwnerPlayerKey
    self.CurTeamIndex = TeamIndex
    self.AC_Tips_UIBP:Show(true, TeamIndex, PlayerKey);
    -- 同一个玩家，再选择一次卡牌
    if IsPlayAnotherRound then
        self:OnPlayerStartAnotherRound(true, TeamIndex, PlayerKey)
    end
end

-- 打出目标卡牌
function AC_Main_UI:PlayCard(TeamIndex, DiceResult)
    print(string.format("AC_Main_UI:OnReceivedDiceResult: P[%d] Result[%d]", TeamIndex, DiceResult));
    ugcprint(UGCGameSystem.GameState.DiceActor:GetAnimPathWithResult(0));
    -- 显示骰子过程动画并设置结果图
    local PlayerController = GameplayStatics.GetPlayerController(UGCGameSystem.GameState, 0);
    UGCAsyncLoadTools:LoadObject(UGCGameSystem.GameState.DiceActor:GetAnimPathWithResult(0), 
        function (ProcessBrush)
            if UE.IsValid(self) then
                self.AC_DiceShow_UIBP.DiceShow_Image:SetBrushFromAsset(ProcessBrush);
            end
        end
    )
    UGCAsyncLoadTools:LoadObject(UGCGameSystem.GameState.DiceActor:GetAnimPathWithResult(DiceResult), 
        function (ResultBrush)
            if UE.IsValid(self) then
                self.AC_DiceShow_UIBP.ResultBrush = ResultBrush;
            end
        end
    )
    --local ProcessBrush = UE.LoadObject(UGCGameSystem.GameState.DiceActor:GetAnimPathWithResult(0));

    --local ResultBrush = UE.LoadObject(UGCGameSystem.GameState.DiceActor:GetAnimPathWithResult(DiceResult));

    -- 播放音效
    UGCGameSystem.GameState.DiceActor:PlayRollDiceVoice();
    if not UE.IsValid(self) then return end
    -- self.AC_DiceShow_UIBP.DiceShow_Image:SetBrushFromAsset(ProcessBrush);
    -- self.AC_DiceShow_UIBP.ResultBrush = ResultBrush
    self.AC_DiceShow_UIBP.Result = DiceResult
    self.AC_DiceShow_UIBP:Show(true);
    

    if self.IsMyRound then
        self.Customizethrow:SetVisibility(ESlateVisibility.Collapsed)
    end
end

-- 显示卡牌选择面板
function AC_Main_UI:ShowCardSelectionPanel(Show)
    ugcprint(string.format("AC_Main_UI:ShowPlaneSelectionPanel:%d", Show and 1 or 0));
    self.AC_Throw_UIBP:SetVisibility(Show and ESlateVisibility.SelfHitTestInvisible or ESlateVisibility.Collapsed)
    --设置当前棋子状态对应的Switcher
    if UGCGameSystem.GameState.FirstFly then
        self.AC_Throw_UIBP.WidgetSwitcher_State:SetActiveWidgetIndex(0)
    else
        self.AC_Throw_UIBP.WidgetSwitcher_State:SetActiveWidgetIndex(1)
        self:ShowFlyPanel(Show)
    end
end

-- 客户端显示所持卡牌UI
function AC_Main_UI:OnUpdateCardUI(PlayerInfos)
    if condition then
        
    end
end

--玩家再选择卡牌（迅捷行动）
function AC_Main_UI:OnPlayerStartAnotherRound(bFind, TeamIndex, PlayerKey)
    print(string.format("AC_Main_UI:OnPlayerStartAnotherRound : %s", ETeameColor[TeamIndex]))
    self.AC_Tips_UIBP:ShowAgain(bFind, TeamIndex, PlayerKey);
end



--[[------------------------------------------UI点击事件------------------------------------------------------]]--

-- 选择打出卡牌的按钮
function AC_Main_UI:SelectCard_Button_OnClicked()
    if self.BGameStart then
        -- ESlateVisibility.Collapsed == 1 , 枚举值，销毁该UI
        self.AC_GameStart_Tips_UIBP:SetVisibility(ESlateVisibility.Collapsed);
        self.BGameStart = false;
    end

    -- 问题3
    UnrealNetwork.CallUnrealRPC(Mode.OwnerController, Mode.OwnerController, "ServerRPC_SelectCard");
    UnrealNetwork.CallUnrealRPC(Mode.OwnerController, Mode.OwnerController, "ServerRPC_ShowSelectCardTips", false);
    --关闭剩余时间显示的UI
    UnrealNetwork.CallUnrealRPC(Mode.OwnerController, Mode.OwnerController, "ServerRPC_ShowRemainTimeTips", false);
end